package com.itheima.easy.service.impl;

import com.itheima.easy.constant.SecurityConstant;
import com.itheima.easy.entity.RoleDept;
import com.itheima.easy.mapper.RoleDeptMapper;
import com.itheima.easy.service.RoleDeptService;
import com.itheima.easy.utils.EmptyUtil;
import com.itheima.easy.vo.DataSecurity;
import com.itheima.easy.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName RoleDeptServiceImpl.java
 * @Description TODO
 */
@Service
public class RoleDeptServiceImpl implements RoleDeptService {

    @Autowired
    RoleDeptMapper roleDeptMapper;

    @Override
    public int batchInsert(List<RoleDept> roleDeptList) {
        return roleDeptMapper.batchInsert(roleDeptList);
    }

    @Override
    public Boolean deleteRoleDeptByRoleId(Long roleId) {
        int flag = roleDeptMapper.deleteRoleDeptByRoleId(roleId);
        if (flag>0){
            return true;
        }
        return false;
    }

    @Override
    public Boolean deleteRoleDeptInRoleId(List<Long> roleIds) {
        int flag = roleDeptMapper.deleteRoleDeptInRoleId(roleIds);
        if (flag>0){
            return true;
        }
        return false;
    }

    @Override
    public DataSecurity findDataSecurityByUserId(List<RoleVo> roleVoList,Long userId) {
        //角色集合不存在，直接返回空
        if (EmptyUtil.isNullOrEmpty(roleVoList)){
            return null;
        }
        //角色集合中是否有自定义数据权限
        List<Long> roleIds = roleVoList.stream()
            .filter(n -> SecurityConstant.DATA_SCOPE_0.equals(n.getDataScope()))
            .map(RoleVo::getId).collect(Collectors.toList());
        //角色集合中无自定义数据权限,返回youselfData为true,只能查看本人权限
        if (EmptyUtil.isNullOrEmpty(roleIds)){
            return DataSecurity.builder().youselfData(true).build();
        }
        //角色集合中有自定义数据权限,返回youselfData为false,查询角色对应的数据权限
        List<RoleDept> roleDeptList = roleDeptMapper.selectInRoleIds(roleIds);
        return DataSecurity.builder()
            .youselfData(false)
            .deptNos(roleDeptList.stream().map(RoleDept::getDeptNo ).collect(Collectors.toList()))
            .build();
    }
}
